package db

import (
	"errors"
	"log"
	"server_cluster/battle/sharemem"
	"strconv"
	"strings"
)

type Config_battle_group struct {
	Id        int32  `gorm:"primary_key;column:Id;autoIncrement:false" csv:"ID"`
	Battle    string `gorm:"column:Battle" csv:"BattleGroup"`
	End_time  int32  `gorm:"column:End_time" csv:"End_time"`
	Condition string `gorm:"column:condition" csv:"VictoryCondition"`
}

func (tmp *Config_battle_group) TableName() string {
	return "config_battle_group"
}

func (tmp *Config_battle_group) getAll() ([]*Config_battle_group, error) {
	var data []*Config_battle_group
	result := Conn.Find(&data)
	return data, result.Error
}

func (tmp *Config_battle_group) LoadData() error {
	data, err := tmp.getAll()
	if err != nil {
		return err
	}
	var myshm = &(sharemem.Myshm.Cfg.Btgp)
	for key, value := range data {
		if key >= sharemem.BATTLE_GROUP_MAX || value.Id <= 0 {
			return errors.New("config_battle_group format error 0")
		}
		myshm[key].Id = value.Id
		if len(value.Battle) == 0 {
			return errors.New("config_battle_group format error 00")
		}

		a_list := strings.Split(value.Battle, ";")
		if len(a_list) > sharemem.BATTLE_GROUP_BATTLE {
			return errors.New("config_battle_group format error 000")
		}
		for k, v := range a_list {
			arg, err := strconv.Atoi(v)
			if err != nil {
				return errors.New("config_battle_group format error 0000")
			}
			myshm[key].Battle[k] = int32(arg)
		}

		myshm[key].End_time = value.End_time
		if len(value.Condition) > 0 {
			a_list := strings.Split(value.Condition, ";")
			if len(a_list) > sharemem.BATTLE_PARAM_MAX1 {
				return errors.New("config_battle_group format error 1")
			}
			for k, v := range a_list {
				b_list := strings.Split(v, "|")
				if len(b_list) > sharemem.BATTLE_PARAM_MAX2 {
					return errors.New("config_battle_group format error 11")
				}
				for k1, v1 := range b_list {
					arg, err := strconv.Atoi(v1)
					if err != nil {
						return errors.New("config_battle_group format error 111")
					}
					myshm[key].Condition[k][k1] = int32(arg)
				}
			}
		}
	}
	log.Println("load config_battle_group completed.")
	return nil
}
